import 'dart:async';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/animation/voice_animation_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/friends_circle_dao.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/model/friends_circle_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/pages/contacts/conversation_friend_page.dart';
import 'package:changxindianzishangwu/pages/find/send_dynamic_page.dart';
import 'package:changxindianzishangwu/pages/message/chat/video_message_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/common_page.dart';
import 'package:changxindianzishangwu/widget/dynamic_dialog.dart';
import 'package:changxindianzishangwu/widget/nine_old_widget.dart';
import 'package:changxindianzishangwu/widget/web_view.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart' as Dio;
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';

///朋友圈
class FindPage extends StatefulWidget {
  String userId;

  ///看好友朋友圈是 true
  bool isOnlyUser;

  FindPage(this.userId, {this.isOnlyUser = false});

  @override
  _FindPageState createState() => _FindPageState();
}

class _FindPageState extends State<FindPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  String resultString = "";

  @override
// TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  int page = 0;

  List<FriendsCircleBean> _lists = [];
  UserInfo _userInfo;

  V2TimUserFullInfo _info;
  int _audiosPosition = -1;

  Widget _headViewWidget;

  getDataList() async {
    FriendsCircleModel _model = await FriendsCircleDao.getFriendsCircleList(
        page, widget.userId, widget.isOnlyUser);
    List<FriendsCircleBean> list = [];

    if (isRefresh) {
      _lists.clear();
      isRefresh = false;
      _refreshController.refreshFailed();
      _refreshController.loadComplete();
    }
    if(widget.isOnlyUser){
      _refreshController.loadNoData();
    }

    if (isLoading) {
      isLoading = false;
      if (list.isEmpty) {
        // print('---啦啦啦-pageIndex--$page');
        _refreshController.loadNoData();
      } else
        _refreshController.loadComplete();
    }
    if (_model.resultCode != 1) {
      return;
    }
    _lists.addAll(_model.data);
    if (mounted) setState(() {});
  }

  AnimationController _colorAnimationController;
  Animation _colorTween, _iconColorTween;

  @override
  void initState() {
    _colorAnimationController =
        AnimationController(vsync: this, duration: Duration(seconds: 0));
    _colorTween = ColorTween(begin: Colors.transparent, end: Colors.white)
        .animate(_colorAnimationController);
    _iconColorTween = ColorTween(begin: Colors.white, end: Colors.black)
        .animate(_colorAnimationController);
    _refreshController = RefreshController(initialRefresh: false);
    _initRecordMp3();
    if (widget.isOnlyUser) {
      _headViewWidget = _headView();
    }

    super.initState();
    if (widget.isOnlyUser) {
      _refreshController.loadNoData();
    }
    getDataList();
  }

  ///如果查看单个用户朋友圈  需要调用 获取该用户的用户信息
  _getOnlyUser() async {
    UserInfoModel _model =
        await FriendsCircleDao.getFriendsUserInfo(widget.userId);
    if (_model.resultCode != 1) {
      toast(_model.resultMsg);
      return;
    }
    return _model.data;
  }

  @override
  void dispose() {
    // _tapGestureRecognizer.dispose();
    // TODO: implement dispose
    recordPlugin.dispose();
    super.dispose();
  }

  Widget _sliverItem(int i) {
    FriendsCircleBean bean = _lists[i];
    // String time = "${DateTime.fromMillisecondsSinceEpoch(bean.time * 1000)}";

    return Container(
      key: UniqueKey(),
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(right: width(15)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ListTile(
            dense: true,
            contentPadding: EdgeInsets.symmetric(horizontal: width(15)),
            leading: HeadView(
              bean.avatar,
              width(40),
              width(40),
            ),
            title: Text(
              bean.nickname,
              style: TextStyle(fontSize: sp(14)),
            ),
            // subtitle: Text(
            //   DateUtil.formatDateMs(bean.time * 1000,
            //       format: DateFormats.y_mo_d_h_m),
            //   style: TextStyle(
            //       fontSize: sp(11), color: ZdColor.rgba(153, 153, 153, 1)),
            // ),
            onTap: () {
              _friendsDetails(i);
            },
          ),
          bean.body.text != "" ? _textContent(bean.body.text) : SizedBox(),
          _mediaContent(i),
          _commentLayout(i),
          SizedBox(
            height: height(10),
          ),
          Divider(
            height: 1,
            indent: ScreenUtil().setWidth(10),
            color: ZdColor.rgba(241, 241, 241, 1),
            thickness: ScreenUtil().setHeight(1),
          ),
        ],
      ),
    );
  }

  ///点击跳转到好友详情
  void _friendsDetails(int i) {
    AddressBookModel _model = AddressBookModel();
    _model.userId = _lists[i].userId.toString();
    _model.name = _lists[i].nickname;
    _model.headerUrl = _lists[i].avatar;
    Get.to(() => ConversationFriendPage(
          model: _model,
        ));
    // try {
    //   Future<V2TimValueCallback<List<V2TimFriendInfoResult>>>
    //   v2TimFriendInfoResult = TencentImSDKPlugin
    //       .v2TIMManager.v2TIMFriendshipManager
    //       .getFriendsInfo(userIDList: [_lists[i].userId.toString()]);
    //
    //   v2TimFriendInfoResult.then((value) {
    //     if (value.data.length == 0) {
    //       toast("暂未查找到该好友");
    //     } else {
    //       print("二维码 跳转页面：UserCheckPage");
    //
    //       Future.delayed(Duration(milliseconds: 500), (){
    //
    //         V2TimFriendInfo _friendsinfo=value.data[0].friendInfo;
    //         AddressBookModel _model=AddressBookModel();
    //         _model.userId=_friendsinfo.userID;
    //         _model.name=ObjectUtil.isEmptyString(_friendsinfo.friendRemark)?_lists[i].nickname:_friendsinfo.friendRemark;
    //         _model.headerUrl=_lists[i].avatar;
    //         // _model.self=_friendsinfo.s;
    //         Get.to(() =>
    //             UserCheckPage(
    //               userId: user.data[0].userId.toString(),
    //               ziyuId: user.data[0].account.toString(),
    //               userEntity: value.data[0].friendInfo.userProfile,
    //             ));
    //
    //       });
    //     }
    //   });
    // } catch (e) {
    //   print(e);
    // }
  }

  List<InlineSpan> _getContentSpan(String text) {
    List<InlineSpan> _contentList = [];

    RegExp exp = new RegExp(
        r'(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?');
    // text = "如果https://www.baidu.com这是一段文本但是里面包含了连接";
    Iterable<RegExpMatch> matches = exp.allMatches(text);

    int index = 0;
    matches.forEach((match) {
      String c = text.substring(match.start, match.end);
      print('RegExp 分割：$c');
      if (match.start == index) {
        index = match.end;
      }
      if (index < match.start) {
        String a = text.substring(index == 0 ? 0 : index + 1, match.start);
        // print('---地址-内容AAAA--$a');
        index = match.end;
        _contentList.add(
          TextSpan(text: a),
        );
      }

      if (RegexUtil.isURL(c)) {
        _contentList.add(TextSpan(
            text: c,
            style: TextStyle(color: Colors.blue),
            recognizer: new TapGestureRecognizer()
              ..onTap = () {
                Get.to(WebViewExample(
                  url: text.substring(match.start, match.end),
                ));
              }));
      } else {
        _contentList.add(
          TextSpan(text: c),
        );
      }
    });
    if (index < text.length) {
      String a = text.substring(index, text.length);
      // print('---地址-内容BBBB--$a');
      _contentList.add(
        TextSpan(text: a),
      );
    }

    return _contentList;
  }

  Container _textContent(String text) {
    List<InlineSpan> _contentList = _getContentSpan(text);

    return Container(
      margin: EdgeInsets.only(left: width(15), right: width(15)),
      alignment: Alignment.centerLeft,
      child: _contentList.isEmpty
          ? Text(
              text,
              style:
                  TextStyle(fontSize: sp(14), color: AppColor.colorDefaultText),
            )
          : Text.rich(TextSpan(children: _contentList)),
    );
  }

  ///动态item下方的评论点赞更多 仅展示更多 还要判断是自己的时候才显示
  _commentLayout(position) {
    return (widget.userId == getUserId() &&
            "${_lists[position].userId}" == getUserId())
        ? Row(
            children: <Widget>[
              // Container(
              //   margin: EdgeInsets.only(left: width(15)),
              //   child: SvgPicture.asset(
              //     "images/yes.svg",
              //     width: width(14),
              //     height: height(14),
              //   ),
              // ),
              // Container(
              //   margin: EdgeInsets.only(left: width(2)),
              //   child: Text(
              //     "123",
              //     style: TextStyle(fontSize: sp(15)),
              //   ),
              // ),
              // Container(
              //   margin: EdgeInsets.only(left: width(40)),
              //   child: SvgPicture.asset(
              //     "images/pinglun.svg",
              //     width: width(14),
              //     height: height(14),
              //   ),
              // ),
              // Container(
              //   margin: EdgeInsets.only(left: width(2)),
              //   child: Text(
              //     "123",
              //     style: TextStyle(fontSize: sp(15)),
              //   ),
              // ),
              Expanded(
                child: Text(""),
                flex: 1,
              ),

              InkWell(
                onTap: () {
                  _editDyDialog(position);
                },
                child: Container(
                  padding: EdgeInsets.only(
                      top: width(7),
                      right: width(15),
                      bottom: width(7),
                      left: width(15)),
                  child: Icon(
                    Icons.more_horiz,
                    size: 16,
                    color: AppColor.colorGrey153,
                  ),
                ),
              ),
            ],
          )
        : Text("");
  }

  ///新消息提示框
  Container _messageView() {
    return Container(
      width: MediaQuery.of(context).size.width,
      alignment: Alignment.center,
      child: Container(
        width: width(140),
        height: height(34),
        padding: EdgeInsets.all(width(1)),
        margin: EdgeInsets.only(top: height(5)),
        decoration: BoxDecoration(
            color: AppColor.colorDefaultText,
            borderRadius: BorderRadius.circular(radius(5))),
        child: Row(
          children: <Widget>[
            HeadView(
              HEADER_URL,
              width(28),
              width(28),
            ),
            SizedBox(
              width: width(27),
            ),
            Text(
              "7 条新消息",
              style: TextStyle(fontSize: sp(12), color: Colors.white),
            )
          ],
        ),
      ),
    );
  }

  ///朋友圈 背景 附近头像名称简介
  Widget _headView() {
    if (!widget.isOnlyUser) {
      _userInfo.avatar = _info == null ? _userInfo.avatar : _info.faceUrl;
      _userInfo.nickname = _info == null ? _userInfo.nickname : _info.nickName;
      _userInfo.description =
          _info == null ? _userInfo.description : _info.selfSignature;
      return _userHead(_userInfo);
    } else
      return FutureBuilder(
          future: _getOnlyUser(),
          builder: (context, sp) {
            if (sp.connectionState == ConnectionState.done && sp.data != null) {
              return _userHead(sp.data);
            } else {
              return SizedBox(
                height: ScreenUtil().setHeight(400),
              );
            }
          });
  }

  SizedBox _userHead(UserInfo value) {
    Widget defalutBg = Container(
        child: Image.asset(
      "images/bg_default_find.jpg",
      fit: BoxFit.cover,
    ));
    return SizedBox(
      height: ScreenUtil().setHeight(400),
      child: Stack(
        children: [
          Container(
            height: ScreenUtil().setHeight(350),
            child: Stack(
              children: [
                InkWell(
                  onTap: () {
                    if (widget.userId != getUserId()) return;
                    _selectAction();
                  },
                  child: Container(
                      width: double.infinity,
                      height: ScreenUtil().setHeight(350),
                      child: CachedNetworkImage(
                        placeholder: (context, url) {
                          return defalutBg;
                        },
                        errorWidget: (context, url, e) {
                          return defalutBg;
                        },
                        imageUrl: value.msgBackGroundUrl != null
                            ? value.msgBackGroundUrl
                            : BACKGROUND_IMAGE,
                        fit: BoxFit.cover,
                        height: ScreenUtil().setHeight(350),
                      )),
                ),
                Container(
                  child: Image.asset(
                    "images/ic_mask_top.png",
                    width: double.infinity,
                  ),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Image.asset(
                    "images/ic_mask_bo.png",
                    width: double.infinity,
                  ),
                ),
              ],
            ),
          ),
          Positioned(
              bottom: height(0),
              right: ScreenUtil().setWidth(15),
              child: Row(
                children: [
                  Container(
                    height: height(70),
                    margin: EdgeInsets.only(right: width(10)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Center(
                          child: Text(
                            value.nickname,
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(18),
                                color: Colors.white,
                                fontWeight: FontWeight.w300),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: height(10)),
                          alignment: Alignment.centerRight,
                          constraints: BoxConstraints(
                            maxWidth:
                                MediaQuery.of(context).size.width - width(95),
                          ),
                          child: Text(
                            value == null || value.description == null
                                ? ""
                                : value.description,
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(12),
                              color: Color.fromRGBO(153, 153, 153, 1),
                            ),
                            maxLines: 2,
                            softWrap: true,
                            overflow: TextOverflow.ellipsis,
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: height(20)),
                    child: HeadView(
                      value.avatar,
                      width(60),
                      width(60),
                    ),
                  ),
                ],
              )),
          // Positioned(
          //   bottom: ScreenUtil().setHeight(0),
          //   right: ScreenUtil().setWidth(55),
          //   left: ScreenUtil().setWidth(8),
          //   child:
          // ),
        ],
      ),
    );
  }

  ///是否在加载更多
  bool isLoading = false;
  bool isRefresh = false;
  RefreshController _refreshController;
  BuildContext _context;

  void _onRefresh() async {
    page = 0;
    isRefresh = true;
    print("success 刷新 $page");
    getDataList();
  }

  void _onLoading() async {
    page++;
    isLoading = true;
    print("success 加载 $page");
    getDataList();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    if (!widget.isOnlyUser) {
      _info = Provider.of<UserModel>(context).info;
      _userInfo = getUserInfo();
      _headViewWidget = _headView();
    }

    // _info = null;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);

    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      body: Stack(
        children: [
          NotificationListener<ScrollNotification>(
              onNotification: _scrollListener,
              child:
                  _smartRefresher(_refreshController, _onRefresh, _onLoading)),
          _appTitle(),
        ],
      ),
    );
  }

  ///标题栏=》根据滚动透明转白
  Container _appTitle() {
    final double topPadding = MediaQuery.of(context).padding.top;
    // print('----topPadding---$topPadding');
    return Container(
      height: 70 + topPadding,
      child: AnimatedBuilder(
        animation: _colorAnimationController,
        builder: (context, child) => Container(
            color: _colorTween.value,
            child: Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 15),
                  child: !widget.isOnlyUser
                      ? Text(
                          "发现",
                          style: TextStyle(
                              color: _iconColorTween.value, fontSize: 20),
                        )
                      : IconButton(
                          onPressed: () {
                            Get.back();
                          },
                          icon: Icon(
                            Icons.arrow_back_ios,
                            color: _iconColorTween.value,
                          ),
                        ),
                ),
                Expanded(child: SizedBox()),
                !widget.isOnlyUser ||
                        (widget.isOnlyUser && widget.userId == getUserId())
                    ? IconButton(
                        icon: Icon(
                          Icons.add_circle_outline,
                          color: _iconColorTween.value,
                        ),
                        onPressed: () {
                          if (getUserDT()) {
                            DynamicDialog.showDialog(_context, () {
                              print('--------_onRefresh-----');
                              _onRefresh();
                            });
                          } else {
                            showCupertinoDialog(
                                context: context,
                                builder: (context) => getDialog(context));
                          }
                        },
                      )
                    : SizedBox()
              ],
            )),
      ),
    );
  }

  CupertinoAlertDialog getDialog(context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text("须知和授权"),
              Text("开启发布动态功能需仔细阅读并同意"),
              Text.rich(TextSpan(
                  text: "《自语APP动态发布条款》",
                  style: TextStyle(color: Colors.blue),
                  recognizer: new TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(WebViewExample(
                        url: HttpUrls.DT,
                      ));
                    })),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text("确定"),
            onPressed: () {
              setUserDT(true);
              Navigator.of(context).pop();
              DynamicDialog.showDialog(_context, () {
                print('--------_onRefresh-----');
                _onRefresh();
              });
            },
          ),
          CupertinoDialogAction(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ]);
  }

  bool _isBottomWidgetShow = false;

  bool _scrollListener(ScrollNotification scrollInfo) {
    final double offset = scrollInfo.metrics.pixels;
    final double maxScrollExtent = scrollInfo.metrics.maxScrollExtent;

    if (maxScrollExtent - offset < 10) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        print("true");
        if (mounted)
          setState(() {
            _isBottomWidgetShow = true;
          });
      });
      Timer(Duration(milliseconds: 3000), () {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          print("timer");
          if (mounted)
            setState(() {
              _isBottomWidgetShow = true;
            });
        });
      });
    }

    if (scrollInfo.metrics.axis == Axis.vertical) {
      if (scrollInfo.metrics.pixels < 0) {
        return false;
      }
      var v = scrollInfo.metrics.pixels / 350;
      // print('滚动：v:$v');

      if (v < 1) {
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
      } else {
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
      }

      _colorAnimationController.animateTo(scrollInfo.metrics.pixels / 350);
      return true;
    }
    return false;
  }

  ///刷新布局
  Widget _smartRefresher(RefreshController _refreshController,
      void _onRefresh(), void _onLoading()) {
    return Container(
      color: Colors.white,
      child: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: MaterialClassicHeader(
          backgroundColor: AppColor.colorTheme,
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              if (_lists.length == 0) {
                body = Text("");
              } else {
                body = Text("没有更多数据了!");
              }
            }
            return Container(
              height: _isBottomWidgetShow ? 55.0 : 0.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: _headViewWidget,
            ),

            /// 2021.7.15 当前版本不显示，不做点赞之类的互动
            // SliverToBoxAdapter(
            //   child: _messageView(),
            // ),
            _sliverList()
          ],
        ),
      ),
    );
  }

  Widget _sliverList() {
    return isRefresh
        ? SliverToBoxAdapter(
            key: UniqueKey(),
            child: CommonPage.loading(() {
              page = 0;
              getDataList();
            }),
          )
        : SliverList(
            key: UniqueKey(),
            delegate:
                SliverChildBuilderDelegate((BuildContext content, int index) {
              return _sliverItem(index);
            }, childCount: _lists.length),
          );
  }

  ///加载图片
  Widget _contentImage(List<FMdeio> photos) {
    return Container(
      margin:
          EdgeInsets.only(top: height(10), left: width(15), right: width(10)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          null != photos || photos.isNotEmpty
              ? NineOldWidget(
                  images: photos,

                  backgroundColor: Colors.white,
                  //资源加载失败显示
                  errorWidget: Icon(Icons.error_outline_rounded),
                )
              : SizedBox()
        ],
      ),
    );
  }

  Future<ImageResult> _getImageHeight(_image) async {
    final Completer<ImageResult> completer = Completer();
    _image.image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((info, b) {
      // print('图片高度：${info.image.height}');
      print('-----------视频图片 _getImageHeight 宽度：${info.image.width} 高度：${info.image.height}');

      completer.complete(ImageResult(
          info.image.width.toDouble(), info.image.height.toDouble()));
    }));

    return completer.future;
  }

  Widget _contentVideo(int position) {
    Body bean = _lists[position].body;

    var w = ScreenUtil().setWidth(MediaQuery.of(context).size.width) ;
    String videoPath = bean.videos[0].oUrl;
    String imageUrl = bean.images != null ? bean.images[0].oUrl : "";
    // return _contentVideoView(w, w, videoPath, imageUrl);

    // print('视频地址--------$videoPath');
    // print('视频图片地址--------$imageUrl');

    print('图片高度:$_getImageHeight(_image)');
    Image _image = Image.network(
      imageUrl,
      scale: 3,
    );

    return bean.videos[0].width!=null
        ? _contentVideoView(bean.videos[0].width,bean.videos[0].height, videoPath, imageUrl)
        : FutureBuilder(
            future: _getImageHeight(_image),
            builder: (context, sp) {
              if (sp.connectionState == ConnectionState.done) {
                double videoWidth = sp.data.width;
                double videoHeight = sp.data.height;

                var caNum=videoHeight>videoWidth?w/3:w/2;

                if (caNum < videoWidth) {
                  videoHeight =caNum/videoWidth * videoHeight;
                  videoWidth = caNum;
                }
                _lists[position].body.videos[0].setWidth = videoWidth;
                _lists[position].body.videos[0].setHeight = videoHeight;
                return Container(
                  width: videoWidth,
                  height: videoHeight,
                  margin: EdgeInsets.only(left: width(15), top: height(10)),
                  child: InkWell(
                    onTap: () {
                      Get.to(VideoMessage(
                        url: videoPath,
                        snapshotUrl: imageUrl,
                        type: 2,
                      ));
                    },
                    child: Container(
                      width: videoWidth,
                      height: videoHeight,
                      child: Stack(
                        children: [
                          HeadView(
                            imageUrl,
                            videoHeight,
                            videoWidth,
                          ),
                          Align(
                            alignment: Alignment.center,
                            child: Icon(
                              Icons.play_circle_outline_rounded,
                              color: Colors.white,
                              size: 30,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                );
              }
              return SizedBox();
            });
  }

  Container _contentVideoView(
      double w, double h, String videoPath, String imageUrl) {
    print('-----------视频图片 _contentVideoView 宽度：$w 高度：$h');

    return Container(
        width: w,
        height: h,
        margin: EdgeInsets.only(left: width(15), top: height(10)),
        child: InkWell(
          onTap: () {
            Get.to(VideoMessage(
              url: videoPath,
              snapshotUrl: imageUrl,
              type: 2,
            ));
          },
          child: Stack(
            children: [
              HeadView(
                imageUrl,
                h,
                w,
              ),
              Align(
                alignment: Alignment.center,
                child: Icon(
                  Icons.play_circle_outline_rounded,
                  color: Colors.white,
                  size: 30,
                ),
              )
            ],
          ),
        ));
  }

  // Future<String> getVideoThumbnail(Body bean) async {
  //   String videoPath = bean.videos[0].oUrl;
  //   if (bean.images.length > 0) {
  //     return bean.images[0].oUrl;
  //   }
  //
  //   return await VideoThumbnail.thumbnailFile(
  //     video: videoPath,
  //     thumbnailPath: (await getTemporaryDirectory()).path,
  //     imageFormat: ImageFormat.JPEG,
  //     quality: 40,
  //   );
  // }

  /**
   * 图片/音频/视频
   */
  Widget _mediaContent(int i) {
    FriendsCircleBean bean = _lists[i];
    switch (bean.body.type) {
      case MediaType.MEDIA_TEXT_IMAGE:
        return _contentImage(bean.body.images);
      case MediaType.MEDIA_TEXT_VIDEO:
        return _contentVideo(i);
      case MediaType.MEDIA_TEXT_VOICE:
        return _contentAudios(i);
    }
    return Text("");
  }

  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();

  /**
   * 播放录音按钮
   */

  _contentAudios(int position) {
    FMdeio audio = _lists[position].body.audios[0];
    print('audio${audio.oUrl}');
    return Container(
      margin: EdgeInsets.only(left: width(15), right: width(5), top: width(10)),
      padding: EdgeInsets.only(right: width(15), left: width(10)),
      width: width(120),
      height: width(30),
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.circular(30.0),
        color: AppColor.bg,
      ),
      child: InkWell(
        onTap: () {
          if (_audiosPosition == position) {
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].body.audios[0].setISPlaying =
                    !_lists[_audiosPosition].body.audios[0].isPlaying;
              });
            }
            pause();
          }
          if (_audiosPosition == -1) {
            _audiosPosition = position;
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].body.audios[0].setISPlaying = true;
              });
            }
            playByPath(_lists[_audiosPosition].body.audios[0].oUrl, "url");
          }

          if (_audiosPosition != position) {
            if (_lists[_audiosPosition].body.audios[0].isPlaying) {
              print('-----------录音  当前正在播放 不可切换');
              return;
            }
            stopPlay();
            _audiosPosition = position;
            if (mounted) {
              setState(() {
                _lists[_audiosPosition].body.audios[0].setISPlaying = true;
              });
            }
            playByPath(_lists[_audiosPosition].body.audios[0].oUrl, "url");
          }
        },
        child: Stack(
          children: [
            Align(
              alignment: Alignment.centerLeft,
              child: VoiceAnimationImage(
                width: width(20),
                height: width(20),
                isStop: audio.isPlaying,
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: Text(
                "${audio.length}s",
                style: TextStyle(
                    fontSize: sp(12), color: AppColor.colorDefaultText),
              ),
            )
          ],
        ),
      ),
    );
  }

  /**
   * -----------------------录音 start------------------------------------------------
   */

  ///初始化语音录制的方法
  void _initRecordMp3() async {
    print('----------初始化音频AA');
    recordPlugin.initRecordMp3();
    recordPlugin.responsePlayStateController.listen((data) {
      print("播放路径   " + data.playPath);
      print("播放状态   " + data.playState);
      if (data.playState == "complete" || data.playState == "false") {
        if (mounted) {
          setState(() {
            _lists[_audiosPosition].body.audios[0].setISPlaying = false;
          });
        }
      }
    });
  }

  ///播放指定路径录音文件  url为iOS播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type) {
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  void stopPlay() {
    recordPlugin.stopPlay();
  }

  /**
   * -----------------------录音 end------------------------------------------------
   */
  /**
   * -----------------------修改朋友圈背景 start------------------------------------------------
   */
  void _selectAction() async {
    int index = await showDialog(context: context, title: '修改朋友圈背景');
    if (index == 1) {
      _photoSelect();
      // Navigator.pop(context, '拍照');
    }
    if (index == 2) {
      _imagesSelect();
      // Navigator.pop(context, '从相册选择');
    }
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '拍摄',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '从相册选择',
              isLastOne: true,
              color: AppColor.colorDialog),
        ]);
  }

  _imagesSelect() async {
    await _handleCameraAndMic();
    await ImagePicker()
        .getImage(source: ImageSource.gallery)
        .then((value) => _updatePhoto(value.path));
  }

  _photoSelect() async {
    await ImagePicker()
        .getImage(source: ImageSource.camera)
        .then((value) => _updatePhoto(value.path));
    // if (pickedFile == null) return;
  }

  _handleCameraAndMic() async {
    // 申请权限

    bool a = await await Permission.photos.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      showToast("请打开图库权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }

  _updatePhoto(String path) async {
    EasyLoading.show(status: "正在上传背景图...");
    Dio.FormData formData = Dio.FormData();
    formData.files.add(MapEntry(
        "files",
        Dio.MultipartFile.fromFileSync(path,
            filename:
                "photo_${new DateTime.now().millisecondsSinceEpoch}.png")));
    DynamicMediaModel value = await UpLoadFileDao.addFile(formData);
    if (value.resultCode == 1) {
      String path = value.data.images[0].oUrl;

      UserInfoModel userInfoModel =
          await UserInfoDao.updateUserInfo("msgBackGroundUrl", path);

      EasyLoading.dismiss();
      if (userInfoModel.resultCode == 0) {
        toast("上传失败${userInfoModel.resultMsg}");
        return;
      }
      if (mounted)
        setState(() {
          _headViewWidget = _headView();
        });
      toast("修改成功");
    } else {
      EasyLoading.dismiss();
      toast("上传失败");
    }
  }

  /**
   * -----------------------修改朋友圈背景 end------------------------------------------------
   */
  /**
   * -----------------------删除动态 start------------------------------------------------
   */
  void _editDyDialog(int position) async {
    await showEditDialog(context: context, title: '删除', position: position);
  }

  Future<int> showEditDialog({
    @required BuildContext context,
    @required String title,
    @required int position,
  }) {
    return showCustomBottomSheet(
        titleColor: Colors.red,
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        titleClick: () {
          _deleteDy(position);
          Navigator.pop(context);
        });
  }

  void _deleteDy(position) async {
    int resultCode = await FriendsCircleDao.deleteMsg(_lists[position].msgId);
    if (resultCode == 1) {
      _lists.removeAt(position);
      if (mounted) {
        setState(() {});
      }
    } else {
      toast("删除失败");
    }
  }

/**
 * -----------------------删除动态 end------------------------------------------------
 */
}

class ImageResult {
  final double width;
  final double height;

  ImageResult(this.width, this.height);
}
